package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Value("D:\\code\\project_one\\reggie_waimai")
    private String outPath;

    @Autowired
    private OrdersService ordersService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String number,String beginTime,String endTime){

        //创建page对象
        Page<Orders> page1 = new Page<>(page,pageSize);

        //创建条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(number != null,Orders::getUserId,number);
        queryWrapper.ge(beginTime != null,Orders::getOrderTime,beginTime);
        queryWrapper.le(endTime != null,Orders::getOrderTime,endTime);
        queryWrapper.orderByDesc(Orders::getCheckoutTime);

        //执行查询
        ordersService.page(page1,queryWrapper);
        List<Orders> records = page1.getRecords();
        records = records.stream().map((item) ->{
            item.setUserName("用户" + item.getUserId());
            return item;
        }).collect(Collectors.toList());
        return R.success(page1);
    }

    @GetMapping("/export")
    public R<String> importToExcel(){
        List<Orders> list = ordersService.list();
        // 写法1 JDK8+
        // since: 3.0.0-beta1
        String fileName = outPath + "reggieOrderExcel" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, Orders.class)
                .sheet("reggieoOrder")
                .doWrite(list);
        return R.success("导出成功");
    }

}
